
import { Button, Divider, message, Modal } from 'antd';
import React, { useState, useRef,useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { TableListItem } from './data.d';
import { router as Router } from 'dva';
import { machineList, delMachine } from '@/services/machine'
import ExportJsonExcel from "js-export-excel"
import { connect } from 'umi';
import { DictState, DictType } from '@/models/dict'
import { DownloadOutlined } from '@ant-design/icons';


const { confirm } = Modal;

interface MachineListProps {
  dispatch: Dispatch<any>;
  osDict: DictType[];
  systemDict: DictType[];
  ownerDict: DictType[];
  envDict: DictType[];
}

const MachineList: React.FC<MachineListProps> = ({dispatch,osDict,systemDict,ownerDict,envDict}) => {

  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);

  useEffect(()=>{
    dispatch({
      type: 'dict/init',
      payload: {},
    });
  },[])
  const systemmap = {}
  systemDict.map(item=>{
    systemmap[item.value] = { text: item.label}
  })
  const osmap = {}
  osDict.map(item=>{
    osmap[item.value] = { text: item.label}
  })
  const ownermap = {}
  ownerDict.map(item=>{
    ownermap[item.value] = { text: item.label}
  })
  const envmap = {}
  envDict.map(item=>{
    envmap[item.value] = { text: item.label}
  })
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '模糊搜索',
      dataIndex: 'searchkey',
      hideInForm: true,
      hideInTable: true,
      initialValue: ''
    },
   
    {
      title: 'ip',
      dataIndex: 'ip',
      render: (text, record: any) => (
        <Router.Link to={`/machine/edit?ID=${record.ID}`}>{text}</Router.Link>
      )
    },
    {
      title: '端口',
      dataIndex: 'port',
      hideInTable: true,
      hideInSearch:true,
      initialValue: ''
    },
    {
      title: '所属业务系统',
      dataIndex: 'system',
      sorter: true,
      valueEnum:systemmap
    },
    {
      title: '用途',
      dataIndex: 'use',
    },
    {
      title: '操作系统',
      dataIndex: 'os',
      sorter: true,
      valueEnum: osmap,
    },
    {
      title: '系统版本',
      dataIndex: 'osversion',
      hideInTable: true,
      hideInSearch:false,
      initialValue: ''
    },
    {
      title: '负责人',
      dataIndex: 'owner',
      sorter: true,
      valueEnum: ownermap,
    },
    {
      title: '环境',
      dataIndex: 'env',
      sorter: true,
      valueEnum: envmap,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      hideInTable: true,
      hideInSearch:true,
    },
    {
      title: '密码',
      dataIndex: 'password',
      hideInTable: true,
      hideInSearch:true,
    },
    
    {
      title: '备注',
      dataIndex: 'deploy',
      hideInTable: true,
      hideInSearch:true,
      initialValue: ''
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInForm: true,
      render: (_, record) => (
        <>
          <Button size="small"  type="primary" onClick={() => {
            confirm({
              title: '温馨提示',
              content: '确定删除记录？',
              onOk() {
                delMachine({ id: record.ID }).then(res => {
                  if (res.code == 0) {
                    message.info('删除成功！')
                    if (actionRef && actionRef.current) {
                      actionRef.current.reload();
                    }
                  }
                })
              }
            });
          }}>
            删除
          </Button>
          <Divider type="vertical" />
          <Router.Link to={`/machine/edit?copy=1&ID=${record.ID}`}>复制</Router.Link>
          <Divider type="vertical" />
          {record.os=='linux' && (
            <><Router.Link target="_blank" to={`/ssh?id=${record.ID}`}>SSH</Router.Link>
              </>)
          }
        </>
      ),
    },
  ];
  const exportExcel = () => {
    const option: any = {};

    machineList({}).then(res => {
      const list = res.data
      const expcolumn = columns.filter(o=>{
         return !o.hideInForm || o.hideInForm==undefined
      });
      option.fileName = `服务器列表${new Date().getFullYear()}${new Date().getMonth()+1}`;
      option.datas = [
        {
          sheetData: list.map((item:any) => {
            const result = {};
            expcolumn.forEach(c => {
                console.log(c.valueEnum)
                if(c.valueEnum != undefined && c.valueEnum[item[c.dataIndex]] != undefined){
                  result[c.dataIndex] = c.valueEnum[item[c.dataIndex]].text
                } else{
                  result[c.dataIndex] =item[c.dataIndex]
                }
            });
            return result;
          }),
          sheetName: 'sheet',     // Excel文件名称
          sheetFilter: expcolumn.map(item => item.dataIndex),
          sheetHeader: expcolumn.map(item => item.title),
          columnWidths: expcolumn.map(() => 10),
        },
      ];
      console.log(option)
      const toExcel = new ExportJsonExcel(option);
      toExcel.saveExcel();
    })

  }
  return (
    <PageContainer>
      <ProTable<TableListItem>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="ID"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={(action, { selectedRows }) => [
          <Router.Link to={`/machine/edit`}>添加</Router.Link>,
          <Divider type="vertical" />,
          <Button icon={<DownloadOutlined />} size={'small'} onClick={exportExcel}>导出</Button>
        ]}
        // toolBarRender={() => [
        //   <Button type="primary" onClick={() => handleModalVisible(true)}>
        //     <PlusOutlined /> 新建
        //   </Button>,
        // ]}
        // request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        request={(params: any) => machineList(params)}
        pagination = {{defaultPageSize:10}}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择 <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项&nbsp;&nbsp;
              </div>
          }
        >
          <Button type="primary">批量删除(暂未支持)</Button>
        </FooterToolbar>
      )}

    </PageContainer>
  );
};

// export default TableList;

export default connect(({ dict }: { dict: DictState }) => ({
  osDict: (dict.dictlist || []).filter(o => o.type == 'os').sort((prev, next) => {
    return prev['sort'] - next['sort']
  }),
  systemDict: (dict.dictlist || []).filter(o => o.type == 'system').sort((prev, next) => {
    return prev['sort'] - next['sort']
  }),
  ownerDict: (dict.dictlist || []).filter(o => o.type == 'owner').sort((prev, next) => {
    return prev['sort'] - next['sort']
  }),
  envDict: (dict.dictlist || []).filter(o => o.type == 'env').sort((prev, next) => {
    return prev['sort'] - next['sort']
  }),
}))(MachineList);
